import http from 'common/js/http/'
import store from 'store/index.js'
// http.config.timeout = 20000;
// 清除定时器工具函数
const clearTimeoutByUrl = (url, requestList) => {
	for (let item in requestList) {
		if (url === requestList[item]['url']) {
			clearTimeout(requestList[item]['timeId']);
		}
	}
}

let service = {};
service._requestCount = 0; // 累加请求次数
service._requestTimeIdList = [];
//设置请求前拦截器
http.interceptor.request = config => {
	//添加通用参数
	config.header = {
		"token": uni.getStorageSync('token'),
		// "token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2Mjg2NjAzOTYsInVzZXJuYW1lIjoiMiJ9.ZcjmIWhNlgPp8hBin2wLGfS0QegkFbqpAWB79-cVS8w",
		"refreshToken": uni.getStorageSync('refreshToken'),
		'Content-type': 'application/x-www-form-urlencoded'
	}
	service._requestCount++;
	// 如果接口请求小于200ms的话 那么就不显示loading
	const timeId = setTimeout(() => {
		/* uni.showLoading({
			title: '加载中',
			mask: true
		}); */
		// store.commit("setLoading",true);
		// console.log(1);
	}, 1000);
	service._requestTimeIdList.push({
		timeId: timeId,
		url: config.url
	});
	// console.log(config.header,'config');
	return config

}
//设置请求结束后拦截器
http.interceptor.response = (response) => {
	const statusCode = response.data.code
	//判断返回状态 执行相应操作
	// uni.hideLoading();
	uni.stopPullDownRefresh();
	service._requestCount--;
	// clear 200ms 后准备展示的loading
	clearTimeoutByUrl(response.config.url, service._requestTimeIdList);
	if (service._requestCount <= 0) {
		// uni.hideLoading();
		// store.commit("setLoading",false);
	}
	// console.log(response,'response');
	// ====================================================
	/* 	if(response.header.token_expired){
			// token1失效了
				http.get('/api/user/refreshToken').then(res => {
					 if (res.data.code == 200) {
						 console.log(res.data.data);
						uni.setStorageSync('token', res.data.data.token)
						uni.setStorageSync('refreshToken', res.data.data.refreshToken)
					 } else {
						 uni.showToast({
							 icon: 'none',
							 title: res.data.msg
						 })
					 }
				 })
		} */
	if (statusCode == 401) { //需要刷新token
		uni.removeStorageSync('token')
		uni.removeStorageSync('refreshToken')
		uni.reLaunch({
			url: '/pages/login/login'
		})
	}
	return response;
}